import {wxUtils} from "./wx/wxUtils";

declare const require;
const SDWMiniSDK = require('./sdk/sdwWx');

class SDKUtils {
  isInit = false;
  openId = null;
  id = null;
  private adCanvas = null;

  private sdk: any;

  async init() {
    if (!wxUtils.isWechat) {
      this.isInit = true;
      return;
    }
    this.sdk = new SDWMiniSDK({
      wxAppId: "wxf3a961d82eec3762",    //微信小游戏的APPID
      channel: "10667",   //平台给予的平台ID
      appId: "2055907532",      // 闪电玩平台的appid
    });
    this.setShare();
    await this.getAuthInfo();
  }

  adObj: any = null;

  private getAuthInfo() {
    return new Promise((resolve, reject) => {
      this.sdk.getAuthInfo({
        success: async (res) => {
          this.openId = res.openid;
          this.id = res.id;
          this.isInit = true;
          resolve(res);
        },
        fail: function (res) {
          reject(res)
        }
      });
    });
  }

  getAdCanvas(onShow: Function, onHidden) {
    if (!this.sdk) {
      return;
    }
    const size = cc.view.getVisibleSize();
    const self = this;
    this.onShow = onShow;
    this.onHidden = onHidden;
    const adObj = new this.sdk.sdwAd({
      width: size.width,  // 游戏可视宽度
      height: size.height,  // 游戏可视高度
      landscape: false,
      id: "2055907532",  // 广告ID，没有则采用appid
      // 广告SDK初始化后的回调
      create: function (data) {
        // console.log('广告组件的信息：', data);
      },
      // 创建失败的回调函数
      fail: function (res) {
        console.log('创建失败：', res);
      },
      // 调用显示广告后的回调，每次变化都会通知show
      show: function (adCanvas) {
        self.onShow(adCanvas)
      },
      // SDK监听到关闭按钮，隐藏回调函数，广告组件隐藏
      hidden: function () {
        self.onHidden();
      }
    });
    this.adObj = adObj;
  }

  showAD() {
    this.adObj.showAD();
  }

  private onHidden() {

  };

  private onShow(adCanvas) {

  }

  setShare() {
    this.onShare(false)
  }

  onShare(isFast = true) {
    if (!this.sdk) {
      return;
    }
    const url = Math.random() > 0.5 ? "http://cdn.app.m3guo.com/img/20186/5b2a466e047ec.png" : "http://cdn.app.m3guo.com/img/20186/5b2a4669cdf96.png";
    this.sdk.onSetShareOperate({
      title: '萌喵上月球',
      imageUrl: url,
      query: '',
      fastShare: isFast,    //是否快速转发，false表示设置
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    });
  }
}

class GameUtils {
  isRestart = false;
  sdk: any;
}

export const gameUtils = new GameUtils();

export const sdkUtils = new SDKUtils();